import redis
import os


def connect_to_redis(host, port, password):
    return redis.StrictRedis(host=host, port=int(port), decode_responses=True, charset='UTF-8', password=password)


def view_data(r, key_pattern='*'):
    keys = r.keys(key_pattern)
    data = {}
    for key in keys:
        value = r.get(key)
        if value:
            data[key] = value
    return data


def add_data(r, key, value):
    r.set(key, value)


def delete_data(r, key):
    r.delete(key)


def main():
    host = input('请输入Redis主机地址: ') or "100.101.225.156"
    port = int(input('请输入Redis端口号: ') or 6379)
    password = input('请输入Redis密码: ') or 'test1234'
    r = connect_to_redis(host=host, port=port, password=password)

    while True:
        os.system('cls')
        print('1. 查看数据')
        print('2. 新增数据')
        print('3. 删除数据')
        print('4. 退出')
        choice = int(input('请选择操作: '))

        if choice == 1:
            os.system('cls')
            key_pattern = input('请输入要查询的键的模式（默认为*）: ') or '*'
            data = view_data(r, key_pattern)
            for key, value in data.items():
                print(f'{key}: {value}')
            input("按回车返回菜单")
        elif choice == 2:
            os.system('cls')
            key = input('请输入要添加的键: ')
            value = input('请输入要添加的值: ')
            add_data(r, key, value)
            print('数据已添加')
            input("按回车返回菜单")
        elif choice == 3:
            os.system('cls')
            data = view_data(r, "*")
            for key, value in data.items():
                print(f'{key}: {value}')
            key = input('请输入要删除的键: ')
            delete_data(r, key)
            print('数据已删除')
            input("按回车返回菜单")
        elif choice == 4:
            break
        else:
            print('无效的选择，请重新输入')


if __name__ == '__main__':
    # r = connect_to_redis("100.101.225.156", 6379, "test1234")
    # r.set("name2", "value2")
    # print(r.get("name2"))
    # print(r.keys("*"))
    main()
